//RTK
import {
  createAsyncThunk,
  createSlice,
  type PayloadAction,
} from "@reduxjs/toolkit";
// 自己的
import { coffeeOrderType, orderType } from "@/type/coffeeType";

const initialState: coffeeOrderType = {
  index: 1,
  shopCar: {
    orderIndex: 0,
    time: "",
    order: [],
  },
  orderList: [],
  allOrder: [],
};

export const fetchCoffeeOrderAction = createAsyncThunk(
  "fetchCoffeeOrder",
  (param, { dispatch }) => {}
);

const coffeeOrderSlice = createSlice({
  name: "coffeeOrder",
  initialState,
  reducers: {
    // 添加到购物车
    changeAddToCarList(state, { payload }: PayloadAction<orderType>) {
      state.shopCar.orderIndex = state.index;
      // 如果加入进来的新咖啡已有，则加杯数
      const foundIndex = state.shopCar.order.findIndex((item) => {
        return (
          payload.id === item.id &&
          payload.size === item.size &&
          payload.iceLevel === item.iceLevel &&
          payload.sugerLevel === item.sugerLevel
        );
      });
      if (foundIndex !== -1) {
        state.shopCar.order[foundIndex].count += 1;
      } else {
        state.shopCar.order.push(payload);
      }
    },
    // 购物车里的杯数更改
    changeCarCount(
      state,
      { payload }: PayloadAction<{ item: orderType; num: number }>
    ) {
      const foundIndex = state.shopCar.order.findIndex((item) => {
        return (
          payload.item.id === item.id &&
          payload.item.size === item.size &&
          payload.item.iceLevel === item.iceLevel &&
          payload.item.sugerLevel === item.sugerLevel
        );
      });
      if (foundIndex !== -1)
        state.shopCar.order[foundIndex].count += payload.num;
    },
    // 清空购物车
    changeCleanCar(state) {
      state.shopCar.order = [];
    },
    // 添加订单
    changeAddOrderList(state, { payload }: PayloadAction<string>) {
      // 将订单给
      state.shopCar.time = payload;

      state.orderList.push(state.shopCar);
      state.allOrder.push(state.shopCar); // 全部订单的查看
      state.index += 1; // 订单号递增
    },
    // 删除订单 (payload传订单第几号)
    changeRemoveOrderList(state, { payload }: PayloadAction<number>) {
      state.orderList.splice(payload, 1);
    },
  },
});

export const {
  changeAddToCarList,
  changeCarCount,
  changeCleanCar,
  changeAddOrderList,
  changeRemoveOrderList,
} = coffeeOrderSlice.actions;
export default coffeeOrderSlice.reducer;
